package data;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

public class ProgramClock implements Runnable{
	private Calendar c;
	private SimpleDateFormat sdf;
	private ArrayList<ClockInterface> updateListenerList;
	private HashMap<String,Calendar> clockList = new HashMap<String,Calendar>();
	
	public ProgramClock(){
		c = Calendar.getInstance();
		sdf= new SimpleDateFormat("H:m:s");
		updateListenerList = new ArrayList<ClockInterface>();
		clockList = new HashMap<String,Calendar>();
	}
	public void addClock(String name){
		clockList.put(name, Calendar.getInstance());
	}
	/**
	 * Returns time
	 * @param name
	 * @return Time in seconds
	 */
	public double getClockTime(String name){
		if(!clockList.containsKey(name)){
			//if it does not contain this key return a string with an error
			return 0.0;
		}
		Calendar cal = clockList.get(name);
		Calendar current = Calendar.getInstance(); 
		clockList.remove(name);
		return (current.getTimeInMillis() - cal.getTimeInMillis());
	}
	public String getTime(){
		return sdf.format(c.getTime());
	}
	/**
	 * Update the clock and any listeners once per second
	 */
	@Override
	public void run() {
		while(true){
			try {
				c = Calendar.getInstance();
				/**
				 * Testing
				 */
				//c.add(Calendar.MINUTE, 47);
				
				for(int i =0;i<updateListenerList.size();i++){
					updateListenerList.get(i).update(c);
				}
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				continue;
			}
		}
	}
	public void addClockInterfaceListener(ClockInterface subject){
		updateListenerList.add(subject);
	}
	public void removeClockInterfaceListener(ClockInterface subject){
		updateListenerList.remove(subject);
	}
	public String getTime(String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(c.getTime());
	}
}
